<?php

namespace App\Config;

class connectRedis{

    protected $redis;
    protected $config = '';
    /**
     * 静态成品变量 保存全局实例
     */
    private static $_instance = array();

    /**
     * 静态工厂方法，返还此类的唯一实例
     */
    public static function getInstance($config = array())
    {
        $key = md5(implode(":", $config));
        //判断实例是否存在
        if (!isset(self::$_instance[$key])) {
            self::$_instance[$key] = new self();
            self::$_instance[$key]->config = $config;
            self::$_instance[$key]->redis = new \Redis;
            $host = isset($config["host"]) ? $config["host"] : "127.0.0.1";
            $port = isset($config["port"]) ? $config["port"] : 6379;
            $password = isset($config["password"]) ? $config["password"] : "";
            $db = isset($config["db"]) ? $config["db"] : 0;
            try {
                self::$_instance[$key]->redis->pconnect($host, $port);
                if ($password) {
                    self::$_instance[$key]->redis->auth($password);
                }
                self::$_instance[$key]->redis->select($db);
            } catch (\RedisException $e) {
                echo 'redis error ' . $e->getMessage() . $e->getCode() . "\n";
                unset(self::$_instance[$key]);
                return self::getInstance($config);
            }
        }
        return self::$_instance[$key];
    }

    /**
     * @param $method
     * @param $params
     * @return mixed
     */
    public function __call($method, $params)
    {
        try {
            $ret = call_user_func_array(array($this->redis, $method), $params);
            return $ret;
        } catch (\Exception $e) {
            echo 'redis error ' . $e->getMessage() . $e->getCode() . "\n";
            $config = $this->config;
            $key = md5(implode(":", $config));
            //销毁实例并重新创建实例
            unset(self::$_instance[$key]);
            $this->redis = self::getInstance($config)->redis;
            //重新执行
            return call_user_func_array(array($this->redis, $method), $params);
        }
    }


}
